/**
 *
 */
package com.yangtao.prototype.listener;

import com.yangtao.framework.util.PropertyUtil;
import com.yangtao.prototype.common.util.DbUnitUtil;
import com.yangtao.prototype.system.domain.MenuTree;
import org.dbunit.dataset.ITable;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.Properties;

/**
 * @author 杨涛
 */
public class SystemInitalListenner implements ServletContextListener {
	Integer count = 0;

	@Override
	public void contextDestroyed(ServletContextEvent arg0) {
	}

	@SuppressWarnings("unchecked")
	@Override
	public void contextInitialized(ServletContextEvent event) {
		File initalData = new File(event.getServletContext().getRealPath("/WEB-INF/initalData.xml"));

		Connection connection = null;
		/**
		 * 增加菜单数据
		 */
		InputStream stream = null;
		MenuTree first = null;
		try {
			connection = getConnection();
			connection.setAutoCommit(false);
			DbUnitUtil dbUnitUtil = new DbUnitUtil();
			dbUnitUtil.setConnection(connection);
			dbUnitUtil.refreshData(initalData);

			/**
			 * 初始化菜单数据
			 */
			ITable result = dbUnitUtil.query("sys_menu", "select max(level) as maxLevel from sys_menu");
			Integer maxlevel = null;
			if (result.getRowCount() > 0) {
				maxlevel = (Integer) result.getValue(0, "maxLevel");
			}
			maxlevel = maxlevel == null ? 0 : maxlevel;
			for (int i = maxlevel; i > 0; i--) {
				//菜单和功能权限做了关联了，如果要删除菜单，要先删除功能权限
				dbUnitUtil.executeSql("delete from sys_fun_auth " +
						"where exists (select 1 from sys_menu m where m.id=menuId and m.level=?)", i);
				//删除菜单
//				menuTreeDao.batchExecute("delete from MenuTree where level=?", i);
				dbUnitUtil.executeSql("delete from sys_menu where level = ?", i);
//				executeSql(connection, "delete from sys_menu where level = ?", i);

			}
			SAXReader reader = new SAXReader();
			stream = getClass().getClassLoader()
					.getResourceAsStream("menu.xml");
			Document document = reader.read(stream);
			Element root = document.getRootElement();
			Iterator modules = root.elementIterator("Module");
			while (modules.hasNext()) {
				count++;
				Element element = (Element) modules.next();
//				first = new MenuTree();
				String id = element.attributeValue("id");
				String name = element.attributeValue("name");
				int level = Integer.parseInt(element.attributeValue("level"));
				String icon = element.attributeValue("icon");
				String url = element.attributeValue("url");
				dbUnitUtil.executeSql("insert into sys_menu(id,name,level,icon,url,dispOrder)" +
						"values(?,?,?,?,?,?)", id, name, level, icon, url, count);
				addMoudles(dbUnitUtil, element, id);
			}
			connection.commit();
		} catch (Exception e) {
			e.printStackTrace();
			try {
				connection.rollback();
			} catch (SQLException e1) {
			}
		} finally {
			if (stream != null) {
				try {
					stream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (connection != null) {
				try {
					connection.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * 递归加载子级菜单
	 *
	 * @param element  数据节点
	 * @param parentId 上级菜单Id
	 */
	@SuppressWarnings("unchecked")
	private void addMoudles(DbUnitUtil dbUnitUtil, Element element, String parentId) throws Exception {
		for (Iterator it = element.elementIterator(); it.hasNext(); ) {
			count++;
			Element item = (Element) it.next();
			MenuTree subMenu = new MenuTree();
			String id = item.attributeValue("id");
			String name = item.attributeValue("name");
			Integer level = Integer.parseInt(item.attributeValue("level"));
			String icon = item.attributeValue("icon");
			String url = (item.attributeValue("url"));
			dbUnitUtil.executeSql("insert into sys_menu(id,parentId,name,level,icon,url,dispOrder)" +
					"values(?,?,?,?,?,?,?)", id, parentId, name, level, icon, url, count);
			addMoudles(dbUnitUtil, item, id);
		}
	}

	/**
	 * 创建jdbc连接
	 *
	 * @return 数据库连接
	 * @throws ClassNotFoundException
	 * @throws SQLException
	 */
	private Connection getConnection() throws ClassNotFoundException, SQLException {
		Properties jdbc = PropertyUtil.getProperties("/jdbc.properties");
		String driverName = jdbc.getProperty("jdbc.driverClassName");
		String jdbcUrl = jdbc.getProperty("jdbc.url");
		String username = jdbc.getProperty("jdbc.username");
		String password = jdbc.getProperty("jdbc.password");
		Class.forName(driverName);
		return DriverManager.getConnection(
				jdbcUrl, username, password);
	}
}
